﻿using System;
using System.IO;
using EPiBoost.Core.Infrastructure.CustomRedirects;
using EPiBoost.Core.Infrastructure.DataStore;
using EPiServer;
using EPiServer.Data.Dynamic;
using EPiServer.PlugIn;

namespace EPiBoost.Core.Plugins.Gui.Admin
{
	[GuiPlugIn(DisplayName = "EPiBoost - Custom Redirects", Description = "Manage 301 redirects",
		Area = PlugInArea.AdminMenu, Url = RegisterResources.FilePathCustomRedirects)]
	public partial class CustomRedirects : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			DynamicDataStore store = DataStoreFactory.GetStore(typeof(CustomRedirect));
			var valid = store.StoreDefinition.ValidateAgainstMappings(typeof(CustomRedirect), false);
			
			if (!IsPostBack)
			{
				if (Request["edit"] != null || Request["add"] != null)
				{
					SetupForm();
				}
				else if (Request["import"] != null || Request["import"] != null)
				{
					plhImport.Visible = true;
				}
				else
				{
					if (Request["delete"] != null)
					{
						DeleteRecord();
					}
					if (Request["export"] != null)
					{
						ExportFile();
					}
					LoadRepeater();
				}
			}

		}

		private void ExportFile()
		{
			CustomRedirectsDataStoreHandler dsHandler = new CustomRedirectsDataStoreHandler();
			var redirects = dsHandler.GetHandledCustomRedirects();
			string result = dsHandler.GenerateExport(redirects);
			Context.Response.Clear(); 
			Response.ContentType = "text/plain"; 
			Response.AddHeader("Content-Disposition", "attachment;filename=customRedirects.json");
			Context.Response.Write(result);
			Context.Response.End();
		} 


		private void LoadRepeater()
		{
			CustomRedirectsDataStoreHandler dsHandler = new CustomRedirectsDataStoreHandler();

			if (Request.QueryString["unhandled"] != null)
			{
				rptRedirects.DataSource = dsHandler.GetUnhandledCustomRedirects();
			}
			else
			{
				rptRedirects.DataSource = dsHandler.GetHandledCustomRedirects();
			}

			rptRedirects.DataBind();
			rptRedirects.Visible = true;
		}

		protected void btnImportSave_Click(object sender, EventArgs e)
		{
			if (fluImport.HasFile)
			{
				using (Stream fileStream = fluImport.PostedFile.InputStream)
				using (StreamReader sr = new StreamReader(fileStream))
				{
					var txt = string.Empty;
					string line = null;
					while ((line = sr.ReadLine()) != null)
					{
						txt += line;
					}
					
					CustomRedirectsDataStoreHandler dsHandler = new CustomRedirectsDataStoreHandler();
					var importCount = dsHandler.Import(txt, chkImportOverwrite.Checked);

					var url = new UrlBuilder(Request.RawUrl);
					url.QueryCollection.Remove("import");
					url.QueryCollection.Add("importMessage","Imported " + importCount + " rules");
					Response.Redirect(url.ToString());
				}
			}
		 
		}

		protected void btnImportCancel_Click(object sender, EventArgs e)
		{
			var url = new UrlBuilder(Request.RawUrl);
			url.QueryCollection.Remove("import"); 
			Response.Redirect(url.ToString());
		}


		protected void btnSave_Click(object sender, EventArgs e)
		{
			CustomRedirectHandler fnfHandler = CustomRedirectHandler.Current;

			fnfHandler.SaveCustomRedirects(txtOldUrl.Text, chkStart.Checked, txtNewUrl.Text, chkAppend.Checked, chkOverride.Checked, chkQuerystring.Checked);

			var url = new UrlBuilder(Request.RawUrl);
			url.QueryCollection.Remove("edit");
			url.QueryCollection.Remove("add");
			Response.Redirect(url.ToString());

		}

		protected void btnCancel_Click(object sender, EventArgs e)
		{
			var url = new UrlBuilder(Request.RawUrl);
			url.QueryCollection.Remove("edit");
			url.QueryCollection.Remove("add");
			Response.Redirect(url.ToString());
		}

		private bool SetupForm()
		{
			if (Request["edit"] != null && Request["oldurl"] != null)
			{

				CustomRedirectHandler fnfHandler = CustomRedirectHandler.Current;
				var redirect = fnfHandler.CustomRedirects.Find(Server.UrlDecode(Request["oldurl"]), true);
				if (redirect != null)
				{
					txtOldUrl.Text = redirect.OldUrl;
					chkStart.Checked = redirect.MatchStart;
					txtNewUrl.Text = redirect.NewUrl;
					chkAppend.Checked = !redirect.WildCardSkipAppend;
					chkOverride.Checked = redirect.OverrideExisting;
					chkQuerystring.Checked = redirect.MaintainQuerystring;

					plhEdit.Visible = true;
					return true;
				}
			}
			else if (Request["add"] != null)
			{
				plhEdit.Visible = true;
				return true;
			}
			return false;
		}

		private void DeleteRecord()
		{
			if (Request["delete"] != null && Request["oldurl"] != null)
			{
				CustomRedirectHandler fnfHandler = CustomRedirectHandler.Current;
				var redirect = fnfHandler.CustomRedirects.Find(Server.UrlDecode(Request["oldurl"]), true);
				if (redirect != null)
				{
					new CustomRedirectsDataStoreHandler().DeleteCustomRedirect(Server.UrlDecode(Request["oldurl"]));
				}
			}
		}

	}
}